﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TempMonitor
{
    class Log
    {
        const string logFilePath = "./log.txt";
        const string logFilePathOld = "./log_old.txt";
        static StreamWriter swLogFile;
        static Mutex mutex = new Mutex();
        public static void OpenLog()
        {
            if (File.Exists(logFilePath) == true)
            {
                if (File.Exists(logFilePathOld) == true)
                {
                    File.Delete(logFilePathOld);
                }
                File.Copy(logFilePath, logFilePathOld);
                File.Delete(logFilePath);
            }
            swLogFile = new StreamWriter(logFilePath, true, Encoding.Unicode);
        }

        public static void CloseLog()
        {
            swLogFile.Close();
            swLogFile.Dispose();
            mutex.Close();
        }
        public static void WriteLog(string msg)
        {
            try
            {
                mutex.WaitOne();
                Console.WriteLine(msg);
                swLogFile.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "\t" + msg);
                swLogFile.Flush();
                mutex.ReleaseMutex();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }
        }
    }
}
